<template>
<el-dialog
    :title="title"
    v-model="dialogVisible"
    width="30%"
    :before-close="handleClose" :append-to-body="true">
    <el-form size="small" :model="form" ref="form" label-width="100px" class="demo-ruleForm">
      <el-form-item
        :label="$t('common.category_name')"
        prop="groupName"
        :rules="[{  required: true,  message: $t('common.name_required')}]"


      >
        <el-input type="age" v-model="form.groupName" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" @click="handleClose">{{$t('common.cancel_action')}}</el-button>
        <el-button size="small" type="primary" @click="submitForm()">{{$t('common.submit')}}</el-button>
      </el-form-item>
    </el-form>

  </el-dialog>
</template>

<script>
import FileApi from '@/api/file.js';
export default {
  data() {
    return {
      /*是否显示*/
      dialogVisible: true,
      title: $t("common.add_category"),
      /*from表单模型*/
      form: {
        groupName: '',
        groupId: 0
      }
    };
  },
  props: ['category', 'fileType'],
  created() {
    if (this.category != null) {
      this.form.groupName = this.category.groupName;
      this.form.groupId = this.category.groupId;
      this.title = $t("common.edit_category");
    } else {
      this.form.groupName = '';
      this.form.groupId = 0;
      this.title = $t("common.add_category");
    }
  },
  methods: {
    /*添加图片类别*/
    addCategory: function () {
      let self = this;
      FileApi.addCategory({
        groupName: self.form.groupName,
        groupType: self.fileType
      }).then(data => {
        ElMessage({
          message: $t("common.add_success"),
          type: 'success'
        });
        self.handleClose({
          status: 'success'
        });
      }).catch(error => {
        ElMessage.error($t("common.add_failed"));
      });
    },
    /*修改图片类别*/
    editCategory: function () {
      let self = this;
      let param = {
        groupName: this.form.groupName,
        groupId: this.form.groupId
      };
      FileApi.editCategory(param).then(data => {
        ElMessage({
          message: $t("common.edit_success"),
          type: 'success'
        });
        self.handleClose({
          status: 'success'
        });
      }).catch(error => {
        ElMessage.error($t("common.edit_failed"));
      });
    },
    /*提交*/
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.category && this.category.groupId != null) {
            this.editCategory();
          } else {
            this.addCategory();
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    /*关闭弹窗*/
    handleClose(param) {
      this.dialogVisible = false;
      this.$emit('closeCategory', param);
    }
  }
};
</script>

